//
//  BaseSearchVC.swift
//  Employee
//
//  Created by swordjoy on 2017/4/20.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import MJRefresh
import Moya

class OrderSearchVC: BaseVC {

  fileprivate var workOrders: [WorkOrder] = []
  fileprivate var page = PageModel()
  fileprivate var hearderCancle: Cancellable?
  fileprivate var footerCancle: Cancellable?
  
  fileprivate var customNavigationBar: UIView!
  fileprivate var searchView: SJSearchBar!
  fileprivate var tableView: UITableView!
  
  fileprivate var topLabel: UILabel!
  fileprivate var bottomLabel: UILabel!
  fileprivate lazy var resultView: SectionV = {
    
    let view = SectionV(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 30))
    view.title = ""
    view.backgroundColor = GlobalConfig.BGWhiteColor
    view.titleColor = GlobalConfig.TextLightColor
    return view
    
  }()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = GlobalConfig.BGWhiteColor
    
    create()
    searchView.becomeActive()
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    navigationController?.setNavigationBarHidden(true, animated: true)
    GlobalConfig.baiduStatisticsPageViewStart("工单搜索")
  }
  
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    navigationController?.setNavigationBarHidden(false, animated: true)
    GlobalConfig.baiduStatisticsPageViewEnd("工单搜索")
  }
  
  deinit {
    if let temp = hearderCancle { temp.cancel() }
    if let temp = footerCancle { temp.cancel() }
  }

}


// MARK: - action

extension OrderSearchVC {
  
  fileprivate func pullData() {
    
    tableView.mj_footer.isHidden = true
    
    if let _ = tableView.superview {}
    else {
      self.workOrders = []
      self.page.page = "1"
      self.tableView.reloadData()
    }
    
    if searchView.text.isEmpty {
    
      self.workOrders = []
      self.page.page = "1"
      self.resultView.title = ""
      self.topLabel.text = ""
      self.bottomLabel.text = ""
      self.tableView.reloadData()
      return
    }
    
    
    if let temp = hearderCancle { temp.cancel() }
    
    SJApp.showStateBarHUD()
    hearderCancle = WorkorderRequest.shared.searchOrder(search: searchView.text, pagepn: page.headerPage) { (orders, pageModel) in
      SJApp.hideStateBarHUD()
      
      self.workOrders = orders
      self.page = pageModel
      
      if !self.page.hasData {
        self.topLabel.text = "哎呀!"
        self.bottomLabel.text = "没有找到“\(self.searchView.text)”相关工单"
        self.topLabel.isHidden = false
        self.bottomLabel.isHidden = false
        self.tableView.removeFromSuperview()
        return
      } else {
        self.topLabel.isHidden = true
        self.bottomLabel.isHidden = true
        self.view.addSubview(self.tableView)
      }
      
      self.tableView.mj_footer.isHidden = false
      if self.page.hasNextPage {
        
        self.tableView.mj_footer.endRefreshing()
        
      }
      else { self.tableView.mj_footer.isHidden = true }
      
      self.resultView.title = "共搜索到\(self.page.totalAmount ?? "")个结果"
      self.tableView.reloadData()
      
    }
    
  }
  
  @objc fileprivate func footerRefresh() {
    
    footerCancle = WorkorderRequest.shared.searchOrder(search: searchView.text, pagepn: page.nextPage) { (orders, pageModel) in
    
      self.workOrders += orders
      self.page = pageModel
      
      if self.page.hasNextPage { self.tableView.mj_footer.endRefreshing()}
      else { self.tableView.mj_footer.isHidden = true }
      self.tableView.reloadData()
    }
  }
  
}

// MARK: - UITableViewDataSource

extension OrderSearchVC : UITableViewDataSource {
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    return workOrders.count
    
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: WorkOrderCell.identifier) as! WorkOrderCell
    cell.model = workOrders[indexPath.row]
    return cell
    
  }
  
}

// MARK: - UITableViewDelegate

extension OrderSearchVC : UITableViewDelegate {
  
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    
    return WorkOrderCell.height(with: workOrders[indexPath.row])
    
  }
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    SJApp.endEdit()
    
    let vc = OrderDetailBaseVC()
    vc.orderId = workOrders[indexPath.row].id
    vc.orderStatus = OrderHelper.getType(order: workOrders[indexPath.row])
    navigationController?.pushViewController(vc, animated: true)
    
  }
  
  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    return resultView
  }
  
  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 30
  }
  
}

// MARK: - SJSearchBarDelegate

extension OrderSearchVC: SJSearchBarDelegate {
  
  func didBeaginSearch() {
    
  }
  
  func didEndSearch() {
    
    navigationController?.popViewController(animated: true)
    
  }
  
  func didChange(text: String) {
    let t = DispatchTime.now() + 0.5
    DispatchQueue.main.asyncAfter(deadline: t) {
      self.pullData()
    }
  }
  
}

// MARK: - fileprivate

extension OrderSearchVC {
  
  fileprivate func create() {
    
    customNavigationBar = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.navBarHeight))
    customNavigationBar.backgroundColor = UIColor.white
    view.addSubview(customNavigationBar)
    
    searchView = SJSearchBar()
    searchView.backgroundColor = UIColor.white
    searchView.textFieldBackgroundColor = GlobalConfig.BGWhiteColor
    searchView.placeholder = "单号/手机号/标题/发起人"
    searchView.sj.top = 20 + UIScreen.iPhoneX_top
    searchView.delegate = self
    customNavigationBar.addSubview(searchView)
    
    topLabel = UILabel()
    view.addSubview(topLabel)
    topLabel.font = GlobalConfig.system15Font
    topLabel.textColor = GlobalConfig.BGSkyBlueColor
    topLabel.snp.makeConstraints { (make) in
      
      make.centerX.equalToSuperview()
      make.top.equalTo(100 + UIScreen.iPhoneX_top)
      
    }
    
    bottomLabel = UILabel()
    view.addSubview(bottomLabel)
    bottomLabel.font = GlobalConfig.system15Font
    bottomLabel.textColor = GlobalConfig.BGSkyBlueColor
    bottomLabel.numberOfLines = 0
    bottomLabel.textAlignment = .center
    bottomLabel.snp.makeConstraints { (make) in
      
      make.left.equalTo(50)
      make.right.equalTo(-50)
      make.centerX.equalToSuperview()
      make.top.equalTo(topLabel.snp.bottom).offset(5)
      
    }
    
    tableView = UITableView()
    tableView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.frame = CGRect(x: 0, y: customNavigationBar.sj.bottom, width: UIScreen.width, height: UIScreen.height - customNavigationBar.sj.bottom)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.separatorStyle = .none
    let footerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
    footerView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.tableFooterView = footerView
    tableView.register(WorkOrderCell.self, forCellReuseIdentifier: WorkOrderCell.identifier)
    
    tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(footerRefresh))
    tableView.mj_footer.isHidden = true
    
    view.addSubview(tableView)
    
    
  }
  
}


